package com.leetcode;
import java.util.concurrent.Semaphore;
public class DiningPhilosophersGPT {
    private Semaphore[] forks;
    private final Semaphore eatLimit = new Semaphore(4);

    public void DiningPhilosophers() {
        forks = new Semaphore[] {new Semaphore(1), new Semaphore(1), new Semaphore(1), new Semaphore(1), new Semaphore(1)};
    }

    // call the run() method of any runnable to execute its code
    public void wantsToEat(int philosopher,
                           Runnable pickLeftFork,
                           Runnable pickRightFork,
                           Runnable eat,
                           Runnable putLeftFork,
                           Runnable putRightFork) throws InterruptedException {
        int rightFork = (philosopher + 1) % 5;

        // 先尝试获取信号量，如果没有获得则一直等待
        eatLimit.acquire();
        forks[philosopher].acquire();
        forks[rightFork].acquire();

        pickLeftFork.run();
        pickRightFork.run();

        eat.run();

        putLeftFork.run();
        forks[philosopher].release();

        putRightFork.run();
        forks[rightFork].release();

        eatLimit.release();
    }
}
